<template>
  <div class="research-project-form">
    <el-form :model="form" label-width="120px" size="small">
      <el-form-item label="项目类型" required>
        <el-select v-model="form.projectType" placeholder="请选择项目类型">
          <el-option label="创新项目" value="创新项目" />
          <el-option label="导师项目" value="导师项目" />
        </el-select>
      </el-form-item>

      <el-form-item label="项目名称" required>
        <el-input v-model="form.name" placeholder="请输入项目名称" />
      </el-form-item>

      <el-form-item label="项目角色" required>
        <el-select v-model="form.role" placeholder="请选择角色">
          <el-option label="第一作者" value="第一作者" />
          <el-option label="通讯作者" value="通讯作者" />
          <el-option label="合作作者" value="合作作者" />
        </el-select>
      </el-form-item>

      <el-form-item label="项目年份" required>
        <el-date-picker
          v-model="form.year"
          type="year"
          placeholder="选择年份"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button @click="resetForm" style="margin-left: 10px;">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'ResearchProjectForm',
  data() {
    return {
      form: {
        projectType: '',
        name: '',
        role: '',
        year: null
      }
    }
  },
  methods: {
    async handleSave() {
      const studentId = localStorage.getItem('studentId')
      if (!studentId) {
        ElMessage.error('未检测到登录学号，请重新登录')
        return
      }

      const { projectType, name, role, year } = this.form
      if (!projectType || !name || !role || !year) {
        ElMessage.error('请完整填写所有必填字段')
        return
      }

      const projectYear = year instanceof Date ? year.getFullYear() : year

      const payload = {
        studentId: Number(studentId),
        projectType,
        name,
        role,
        year: projectYear
      }

      try {
        const res = await axios.post('/api/researchprojects', payload, {
          headers: { 'Content-Type': 'application/json' },
          withCredentials: true
        })

        if (res.data === 1 || res.data.code === 200 || res.data > 0) {
          ElMessage.success('科研项目保存成功')
          this.resetForm()
        } else {
          ElMessage.error(res.data.message || '保存失败，请稍后重试')
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败，请稍后重试')
      }
    },

    resetForm() {
      this.form.projectType = ''
      this.form.name = ''
      this.form.role = ''
      this.form.year = null
    }
  }
}
</script>

<style scoped>
.research-project-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 24px;
  background-color: #fafafa;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
</style>
